package com.epro.dx.activity;

import android.content.Context;
import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.ToggleButton;
import com.epro.dx.BR;
import com.epro.dx.R;
import com.epro.dx.adapter.CommonRVAdapter;
import com.epro.dx.databinding.ActivityTrackSubscriptBinding;
import com.epro.dx.databinding.TrackLatestNewsBinding;
import com.epro.dx.listenner.CustomAsyncTaskListener;
import com.epro.dx.listenner.SimpleTextWatchListener;
import com.epro.dx.task.GetTrackConfigTask;
import com.epro.dx.task.SetShippingMsgSettingTask;
import com.epro.dx.util.ActivityUtil;
import com.epro.dx.util.DialogUtils;
import com.epro.dx.util.DpPxUtils;
import com.epro.dx.util.IntentUtils;
import com.weipu.common.constants.Constant;
import com.weipu.common.constants.ServerConstant;
import com.weipu.common.facade.model.PushSettingsModel;
import com.weipu.common.util.Logger;
import com.weipu.common.util.NotificationsUtils;
import com.weipu.common.util.StringUtil;
import com.weipu.common.util.utils.JsonFormat;
import com.weipu.common.util.utils.SPUtils;
import java.util.ArrayList;
import java.util.List;

/**
 * 物流订阅页面
 *
 * @author Zenglw
 * @version [2.0, 2017-6-16]
 * @des 2017/7/10 修复当不在编辑框时，清除焦点
 */
public class TrackSubscriptActivity extends BaseFragmentActivity implements CommonRVAdapter.OnItemClickListener, CustomAsyncTaskListener<PushSettingsModel.DataBean> {

    private static final String TAG = "TrackSubscriptActivity";
    ToggleButton trackSwitch;
    EditText trackCustomEt;
    CheckBox trackCheckBox;

    private ActivityTrackSubscriptBinding binding;
    private DialogUtils build;
    private SPUtils spUtils;
    private DialogUtils closeDialogBuild;
    //是否是用户在操作
    private boolean isByUser = true;
    private GridLayoutManager gridManager;
    private List<String> mLatesNews;
    private RecyclerView trackLatestNewsRv;
    private CommonRVAdapter adapter;
    //单选框能不能点击
    private boolean singleChoiceCanClickable;
    //当前单选中选中的下标
    private int curIndex = -1;
    //获取用户配置的异步任务
    private GetTrackConfigTask getTrackConfigTask;
    private SetShippingMsgSettingTask setShippingMsgSettingTask;
    private TextView trackCustomEtHint;
    ///////////////请求相关参数//////////////////
    //推送周期
    private int pushCircle = -1;
    //推送类型 1为物流更新推送 2为按周期推送
    private int pushType = 1;
    //是否推送
    private boolean isPush = true;
    //是否是用户自定义的周期 1为用户自定义的 2为单选的 0 是不设置
    private int CycleSetType;
    ///////////////请求相关参数//////////////////


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
        binding = DataBindingUtil.setContentView(this, R.layout.activity_track_subscript);
        //牛刀  绑定界面
        //设置左边的返回按钮显示
        setLeftBtnContent(true, -1);
        //设置布局
        setTitleContent(R.string.my_account_order_tracking);
        initView();
        //初始化变量的属性
        initProperty();
        //初始化事件
        initEvent();
        //初始化数据
        initData();


    }

    private void initData() {
        //显示加载动画界面
        showLoadingLayout(binding.trackContent);
        showWaitingDialog();
        getTrackConfigTask = new GetTrackConfigTask(TrackSubscriptActivity.this);
        //开启异步任务来获取用户所设置的物流订阅的配置信息
        getTrackConfigTask.execute();

    }

    /**
     * 获取订阅配置成功请求的回调方法
     *
     * @param pushSettingsModel 返回的数据
     */
    @Override
    public void onPostExecute(PushSettingsModel.DataBean pushSettingsModel) {

        //显示界面，隐藏加载动画的界面
        hideAllLayout(binding.trackContent);
        hideWaitingDialog();

        if (pushSettingsModel != null) {
            Logger.e(TAG, JsonFormat.format(pushSettingsModel.toString()));
            //将请求获取到的参数设置给全部变量
            pushType = pushSettingsModel.getType();
            isPush = pushSettingsModel.isIsPush();
            pushCircle = pushSettingsModel.getCycleDate();
            CycleSetType = pushSettingsModel.getCycleSetType();

            //设置到界面上
            setConfig();

            //如果开关打开但是系统没有通知全选，则弹出窗口让用户去设置
            if (isPush && !NotificationsUtils.isNotificationEnabled(this)) {
                showOpenSysDialog();
            }
        } else {
            showErrorLayout(null, R.string.server_busy,
                    R.string.server_suggest, R.drawable.no_internet);
        }
    }

    /**
     * 将服务器的数据设置到界面上去
     */
    private void setConfig() {

        //设置开关的状态
        trackSwitch.setChecked(isPush);
        //根据是否推送设置整个页面的是布局颜色以及是否可以点击
        binding.setIsOpen(isPush);

        //单选款是否可以点击
        singleChoiceCanClickable = isPush;

        if (isPush) {
            if (pushType == 1) {
                //物流更新时推送
                trackCheckBox.setChecked(true);
            } else if (pushType == 2) {
                //按周期推送，在继续判断是用户自定义的还是单选的
                if (CycleSetType == 1) {
                    //用户自定义的
                    trackCustomEt.setText(String.valueOf(pushCircle));
                } else if (CycleSetType == 2) {

                    //单选的
                    switch (pushCircle) {
                        case 1:
                            curIndex = 0;
                            break;

                        case 2:
                            curIndex = 1;

                            break;

                        case 3:
                            curIndex = 2;

                            break;

                        case 7:
                            curIndex = 3;

                            break;

                        default:

                            break;
                    }
                    //直接调用这个方法更新界面，同时还能产生互斥效果
                    onItemClick(binding.getRoot(), curIndex);
                }

            }

        } else {
            clearConfig();
        }
    }

    private void initProperty() {
        spUtils = new SPUtils(getResources().getString(R.string.app_name_en));

        //添加单选按钮
        setLatesRv();

    }


    private void setLatesRv() {
        //添加单选按钮数据
        mLatesNews = new ArrayList<>();
        mLatesNews.add(getResources().getString(R.string.track_every_day));
        mLatesNews.add(getResources().getString(R.string.track_every_two_day));
        mLatesNews.add(getResources().getString(R.string.track_every_three_day));
        mLatesNews.add(getResources().getString(R.string.track_every_week));

        gridManager = new GridLayoutManager(this, 2);
        trackLatestNewsRv.setLayoutManager(gridManager);
        adapter = new CommonRVAdapter(mLatesNews, BR.latestNew, R.layout.track_latest_news) {
            @Override
            protected void onBindingComplete(ViewDataBinding binding, int layoutPosition) {
                if (layoutPosition == curIndex) {
                    ((TrackLatestNewsBinding) binding).trackLatestItemIv.setImageResource(R.drawable.track_check_on);

                } else {
                    ((TrackLatestNewsBinding) binding).trackLatestItemIv.setImageResource(R.drawable.track_check_off);

                }

                if (singleChoiceCanClickable) {
                    binding.getRoot().setEnabled(true);
                } else {
                    binding.getRoot().setEnabled(false);

                }

                if (isPush) {
                    ((TrackLatestNewsBinding) binding).trackLatestItemTv.setTextColor(getResources().getColor(R.color.common_black_text_color));
                } else {
                    ((TrackLatestNewsBinding) binding).trackLatestItemTv.setTextColor(getResources().getColor(R.color.common_gray_text_color));

                }
            }
        };
        adapter.setOnItemClickListener(this);
        trackLatestNewsRv.setAdapter(adapter);
    }

    @Override
    public void onItemClick(View view, int position) {
        curIndex = position;
        binding.trackSingleChoiceHint.setVisibility(View.VISIBLE);
        //将推送类型更改为按周期推送
        pushType = 2;
        //清空其他的选项
        CycleSetType = 2;
        trackCheckBox.setChecked(false);
        trackCustomEt.setText("");
        //清除输入框的焦点
        trackCustomEt.clearFocus();
        adapter.notifyDataSetChanged();

        //将推送周期重新赋值
        switch (position) {
            case 0:
                pushCircle = 1;
                break;
            case 1:
                pushCircle = 2;
                break;
            case 2:
                pushCircle = 3;
                break;
            case 3:
                pushCircle = 7;
                break;
            default:
                break;
        }
    }


    @Override
    protected void onPause() {
        super.onPause();
        if (curIndex == -1 && !trackCheckBox.isChecked() && trackCustomEt.getText().toString().isEmpty()) {
            pushType = 1;
            pushCircle = -1;
            CycleSetType = 0;
        }
        setShippingMsgSettingTask = new SetShippingMsgSettingTask(isPush, pushType, pushCircle, CycleSetType, new CustomAsyncTaskListener<Boolean>() {
            @Override
            public void onPostExecute(Boolean isSuccess) {
                StringUtil.saveConfig("IsPush", isPush + "");
            }
        });
        setShippingMsgSettingTask.execute();
    }

    private void initView() {
        trackSwitch = binding.trackSwitch;
        trackCustomEt = binding.trackCustomEt;
        trackCheckBox = binding.trackCheckBox;
        trackLatestNewsRv = binding.trackRv;
        trackCustomEtHint = binding.trackCustomHint;

        //设置checkbox 选框的大小
        Drawable drawable1 = getResources().getDrawable(R.drawable.track_checkbox_shape);
        drawable1.setBounds(0, 0, DpPxUtils.Dp2Px(this, 15), DpPxUtils.Dp2Px(this, 15));//第一0是距左边距离，第二0是距上边距离，40分别是长宽
        trackCheckBox.setCompoundDrawables(drawable1, null, null, null);//只放右边

    }

    private void initEvent() {
        trackSwitch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (trackSwitch.isChecked()) {
                    boolean sysSwitch = NotificationsUtils.isNotificationEnabled(TrackSubscriptActivity.this);
                    restoreDefaultConfig();
                    binding.setIsOpen(true);

                    if (!sysSwitch) {
                        //应用通知关闭，弹窗开启系统通知权限
                        showOpenSysDialog();
                    }

                    isPush = true;
                } else {
                    //隐藏除开关下面以外的所有提示
                    binding.trackSingleChoiceHint.setVisibility(View.GONE);
                    binding.trackCustomEtHint.setVisibility(View.GONE);
                    boolean isShowDialogWhenClose = spUtils.getBoolean(Constant.Global.WHEN_CLOSE_IS_SHOW_DIALOG, false);
                    if (!isShowDialogWhenClose) {
                        //暂时将按钮设置为打开状态，如果用户点击确定关闭，则再设置为false，如果用户点击了取消关闭，则不处理
                        trackSwitch.setChecked(true);
                        whenCloseDialog();
                    } else {
                        clearConfig();
                        //显示弹窗，To cancel the order tracking subscription, you may miss important notices. Still to cancel it?
                        binding.setIsOpen(false);
                        isPush = false;
                    }
                }
            }
        });

        //当复选框状态的监听回调方法
        trackCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                //清除输入框的焦点
                trackCustomEt.clearFocus();
                if (isChecked) {
                    binding.trackSingleChoiceHint.setVisibility(View.GONE);
                    binding.trackCustomEtHint.setVisibility(View.GONE);

                    //推送类型为当物流更新时推送
                    pushType = 1;
                    pushCircle = -1;
                    CycleSetType = 0;
                    curIndex = -1;
                    adapter.notifyDataSetChanged();

                }
                //当复选框是选中状态同时编辑框不是空的时候，就把编辑框置空
                if (isChecked && !TextUtils.isEmpty(trackCustomEt.getText().toString())) {
                    trackCustomEt.setText("");
                }
            }
        });


        //当自定义周期文本框内容发生改变的时候的监听回调
        trackCustomEt.addTextChangedListener(new SimpleTextWatchListener() {

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                //屏蔽用户输入的数字不是0开头
                if (charSequence.toString().startsWith("0")) {
                    trackCustomEt.setText("");
                    return;
                }
                if (!TextUtils.isEmpty(charSequence.toString())) {
                    //显示 隐藏的提示
                    binding.trackCustomEtHint.setVisibility(View.VISIBLE);
                    binding.trackSingleChoiceHint.setVisibility(View.GONE);

                    pushType = 2;

                    //捕获NumberFormatException异常
                    try {
                        pushCircle = Integer.parseInt(charSequence.toString());
                    } catch (NumberFormatException e) {
                        pushCircle = 0;
                    }
                    //如果用户所填的数字超过30
                    if (pushCircle > 92) {
                        trackCustomEt.setText("92");//强制设置为92
                        trackCustomEtHint.startAnimation(AnimationUtils.loadAnimation(TrackSubscriptActivity.this, com.weipu.dx_lib.R.anim.shake));
                        trackCustomEt.setSelection(2);
                        return;
                    } else if (pushCircle == 0) {
                        trackCustomEt.setText("0");
                    }

                    trackCheckBox.setChecked(false);
                    CycleSetType = 1;
                    curIndex = -1;
                    adapter.notifyDataSetChanged();
                } else {
                    if (curIndex != -1) {
                        binding.trackCustomEtHint.setVisibility(View.GONE);
                    }

                }
            }
        });

        //点击try Aggin（只有在网络出现问题时才会出现的按钮）
        emptyLayout.findViewById(R.id.try_again).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showLoadingLayout(binding.trackContent);
                executeTask(new GetTrackConfigTask(TrackSubscriptActivity.this));
            }
        });

    }

    /**
     * 重写，当点击屏幕的其他地方（非编辑框），则隐藏弹出来的输入法
     *
     * @param ev
     * @return
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

    /**
     * 判断是否应该隐藏输入法
     *
     * @param v
     * @param event
     * @return true:隐藏 false:显示
     */
    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取物流配置信息
     *
     * @param getTrackConfigTask
     */
    private void executeTask(GetTrackConfigTask getTrackConfigTask) {
        getTrackConfigTask.execute();
    }

    /**
     * 清空用户选择的配置
     */
    private void clearConfig() {
        trackCustomEt.setText("");
        trackCheckBox.setChecked(false);
        curIndex = -1;
        singleChoiceCanClickable = false;
        adapter.notifyDataSetChanged();
    }

    /**
     * 还原默认的配置信息
     */
    private void restoreDefaultConfig() {
        trackCheckBox.setChecked(true);
        singleChoiceCanClickable = true;
        adapter.notifyDataSetChanged();
    }

    /**
     * 当滑动到关闭的时候，显示弹窗，该弹窗只显示一次
     */
    private void whenCloseDialog() {
        View view = LayoutInflater.from(TrackSubscriptActivity.this).inflate(R.layout.dialog_edit_remark, null);
        closeDialogBuild = new DialogUtils.Builder(TrackSubscriptActivity.this)
                .setContentView(view)
                .setEtContent(getResources().getString(R.string.dialog_when_close_hint))
                .setViewClick(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (v.getId() == R.id.btn_yes) {
                            clearConfig();
                            binding.setIsOpen(false);
                            isPush = false;
                            //将开关设置为关闭状态
                            trackSwitch.setChecked(false);

                        }

                        closeDialogBuild.dismiss();

                    }
                }, R.id.btn_yes, R.id.btn_no)
                .build();
        closeDialogBuild.showDialog();
        spUtils.put(Constant.Global.WHEN_CLOSE_IS_SHOW_DIALOG, true);

    }

    /**
     * 提示打开系统权限的弹窗
     */
    private void showOpenSysDialog() {
        View view = LayoutInflater.from(TrackSubscriptActivity.this).inflate(R.layout.dialog_edit_remark, null);
        build = new DialogUtils.Builder(TrackSubscriptActivity.this)
                .setContentView(view)
                .setEtContent(getResources().getString(R.string.dialog_to_sys_hint))
                .setViewClick(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (v.getId() == R.id.btn_yes) {
                            jumpToAppDetailsSettings();
                        }
                        build.dismiss();
                    }
                }, R.id.btn_yes, R.id.btn_no)
                .build();
        build.showDialog();
    }

    /**
     * 跳转到APP系统设置详情，引导用户手动开启通知权限
     */
    private void jumpToAppDetailsSettings() {
        Uri packageURI = Uri.parse("package:" + getPackageName());
        IntentUtils.launchActivityByAction(this, Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
    }

    /**
     * 设置状态栏的颜色
     */
    @Override
    protected void setStateColor() {
//        ActivityUtil.setStatusColor(this, getResources().getColor(R.color.bg_color_f4f4f4), null);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ActivityUtil.setStatusColor(this, getResources().getColor(R.color.white),null);
        }else {
            ActivityUtil.setStatusColor(this, 0 ,null);
        }
    }

    /**
     * 设置标题不滚动
     */
    @Override
    protected void setViewState() {
        topbarTitleTv.setMarqueeRepeatLimit(0);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        getTrackConfigTask.cancel(true);
    }
}
